// 引入参加slice和创建store的函数
import { configureStore, createSlice, createAsyncThunk } from '@reduxjs/toolkit'
// configureStore 创建store
// createSlice 创建slice. slice中包含了reducer和actions

// 创建异步对象
const asyncYyy = createAsyncThunk('yyy', () => {
  // 这个回调要求必须返回一个promise
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // resolve(123)]
      reject(456)
    }, 1000)
  })
})

const slice = createSlice({
  name: 'yyy',
  initialState: { c: 0, msg: '123' },
  reducers: {
    // reducers中有多少个键值对,则表示这里slice生成的reducer函数中有几个case.并且也有对应个数的actionCreator
    add(state, action) {
      // 这个state不是reducer中的state.是reducer中state的代理,所以这个state可以被直接赋值(修改),我们修改了这个state,底层会自动将修改后的state作为reducer函数的返回值
      // action 还是一个action对象
      // console.log(state, action)
      state.c = state.c + 1
    },
    sub(state, action) {
      state.c = state.c - action.payload
    },
  },
  extraReducers(builder) {
    builder.addCase(asyncYyy.pending, (state, action) => {
      console.log('异步正在执行的时候触发')
    })
    builder.addCase(asyncYyy.fulfilled, (state, action) => {
      console.log('异步成功', state, action)
    })
    builder.addCase(asyncYyy.rejected, (state, action) => {
      console.log('异步失败', state, action)
    })
  },
})

// 创建store
const store = configureStore({
  // 这个reducer其实就是合并reducer的代码
  reducer: {
    xxx: slice.reducer,
  },
})

store.subscribe(() => {
  console.log(store.getState())
})
const { add, sub } = slice.actions // 包含了slice中创建出来的actionCreator
// console.log(add())
// console.log(sub(2))
store.dispatch(add())
store.dispatch(add())
store.dispatch(add())

// 执行异步代码
store.dispatch(asyncYyy(999))



 

